﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace Sasa.QualityTools.CodeAnalysis.Core.Utilities
{
    public class ReportGenerator<TEntity>
    {
        private List<ColumnGenerationSetting> settings;


        public ReportGenerator()
        {
            settings = new List<ColumnGenerationSetting>();
        }


        public void RegisterColumn(string header, Func<TEntity, string> valueSelector)
        {
            settings.Add(new ColumnGenerationSetting(header, valueSelector));
        }

        public void Generate(string path, IEnumerable<TEntity> entities)
        {
            using (var writer = new StreamWriter(path))
            {
                writer.WriteLine(String.Join(",", settings.Select(o => Quote(o.Header))));
                foreach (var entity in entities)
                {
                    writer.WriteLine(String.Join(",", settings.Select(o => Quote(o.ValueSelector(entity)))));
                }
            }
        }

        private string Quote(string value)
        {
            return '"' + ((value != null) ? value.Replace("\"", "\"\"") : "") + '"';
        }


        private class ColumnGenerationSetting
        {
            public string Header { get; private set; }

            public Func<TEntity, string> ValueSelector { get; private set; }


            public ColumnGenerationSetting(string header, Func<TEntity, string> valueSelector)
            {
                Header = header;
                ValueSelector = valueSelector;
            }
        }
    }
}
